package com.kd.juhaowan.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;


import com.google.android.material.tabs.TabLayout;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallbackProxy;
import com.kd.juhaowan.R;
import com.kd.juhaowan.http.api.CommonApi;
import com.kd.juhaowan.http.api.ReciveGiftApi;
import com.kd.juhaowan.http.model.GiftModel;
import com.kd.juhaowan.http.model.HttpData;
import com.kd.juhaowan.http.model.MineMessageModel;
import com.kd.juhaowan.http.model.MoreGiftResult;
import com.kd.juhaowan.ui.adapter.BaseRecyclerViewAdapter;
import com.kd.juhaowan.ui.adapter.BaseViewHolder;
import com.kd.juhaowan.ui.adapter.CommonFragmentPagerAdapter;
import com.kd.juhaowan.ui.dialog.ConfirmDialog;
import com.kd.juhaowan.ui.fragment.MoreGiftFragment;
import com.kd.juhaowan.ui.holder.Fuli648ViewHolder;
import com.kd.juhaowan.ui.holder.MineMessageViewHolder;
import com.kd.juhaowan.ui.listener.OnItemDianzanListener;
import com.kd.juhaowan.utils.DeviceUtil;
import com.kd.juhaowan.view.CustomFuliTabView;
import com.kd.juhaowan.view.FulliScollTextView;
import com.kd.juhaowan.view.NoScrollViewPager;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.OnClick;

public class MoreGiftActivity extends BaseActivity  implements OnItemDianzanListener {

    @BindView(R.id.main_activity_tabLayout)
    TabLayout mMainTabLayout;
    @BindView(R.id.main_activity_viewpager)
    NoScrollViewPager mMainViewPager;
    @BindArray(R.array.moregift_tab_text)
    String[] mMainTabText;
    @BindView(R.id.activity_title)
    TextView titleView;
//    @BindView(R.id.gift_listview)
//    RecyclerView recyclerView;
//    @BindView(R.id.activity_title)
//    TextView titleView;

    int[] mMainTabIconResourceId = new int[]{
            R.drawable.tab_moregift_hot_selecter,
            R.drawable.tab_moregift_hot_selecter,
     };

    private BaseRecyclerViewAdapter<MineMessageViewHolder, MineMessageModel> giftAdapter;

    private MoreGiftResult headModel;

    @BindView(R.id.fragment_home_scrollTextView)
    FulliScollTextView mScrollTextView;

    @BindView(R.id.fuli_648list)
    RecyclerView m648ListView;
    private BaseRecyclerViewAdapter<Fuli648ViewHolder, GiftModel> m648Adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        titleView.setText("648暴击");
        setAdapter();
        EasyHttp.post(this).api(new CommonApi("api/welfare/MoreGiftPackages")).request(new HttpCallbackProxy<HttpData<MoreGiftResult>>(this){
            @Override
            public void onHttpSuccess(HttpData<MoreGiftResult> result, boolean cache) {
                super.onHttpSuccess(result, cache);
                headModel = result.getData();
                m648Adapter.resetAdapterData(headModel.getGiftpack());
                mScrollTextView.setData(headModel.getClaim_record());
                initFragmentTab();
            }
        });
    }

    @Override
    protected void reInitDate() {
        EasyHttp.post(this).api(new CommonApi("api/welfare/MoreGiftPackages")).request(new HttpCallbackProxy<HttpData<MoreGiftResult>>(this){
            @Override
            public void onHttpSuccess(HttpData<MoreGiftResult> result, boolean cache) {
                super.onHttpSuccess(result, cache);
                headModel = result.getData();
                m648Adapter.resetAdapterData(headModel.getGiftpack());
                mScrollTextView.setData(headModel.getClaim_record());
                initFragmentTab();
            }
        });
    }

    private void setAdapter(){
        m648Adapter = new BaseRecyclerViewAdapter<Fuli648ViewHolder, GiftModel>() {
            @NonNull
            @Override
            public Fuli648ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                LayoutInflater inflater = LayoutInflater.from(parent.getContext());
                View view = inflater.inflate(R.layout.item_fuli_648, null, false);
                Fuli648ViewHolder holder = new Fuli648ViewHolder(view);
                holder.setOnItemClickListener(getOnItemClickListener());
                return holder;
            }

            @Override
            public void onBindViewHolder(@NonNull Fuli648ViewHolder holder, int position) {
                holder.setDate(getItem(position));
            }
        };

        m648Adapter.setOnItemClickListener(MoreGiftActivity.this);
        m648Adapter.resetAdapterData(null);
        LinearLayoutManager layoutManager = new LinearLayoutManager(MoreGiftActivity.this);
        layoutManager.setOrientation(RecyclerView.HORIZONTAL);

        m648ListView.setLayoutManager(layoutManager);
        m648ListView.setAdapter(m648Adapter);



    }


    @Override
    public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int position) {

    }
    private ConfirmDialog dialog = null;
    @Override
    public void onItemDianzanClick(BaseViewHolder viewHolder, int position) {
        GiftModel model = m648Adapter.getItem(position);
        EasyHttp.post(this).api(new ReciveGiftApi(model.getId(),model.getGame_id(), DeviceUtil.isInstallApp(this,model.getGame_package_name())?1:2)).request(new HttpCallbackProxy<HttpData<GiftModel>>(this){
            @Override
            public void onHttpSuccess(HttpData<GiftModel> result, boolean cache) {
                super.onHttpSuccess(result, cache);
                model.setIs_receive(1);
//                    model.setCode(result.getData().getCode());
                m648Adapter.notifyItemChanged(position,model);
                startDownload(model);

                ConfirmDialog.Builder builder = new ConfirmDialog.Builder(MoreGiftActivity.this);
                builder.setMessage(result.getMessage());
                builder.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        gotGameInfo(model);
                        dialog.dismiss();
                    }
                });
                dialog = builder.create();
                dialog.show();

            }
        });
    }


    @Override
    public void onPause() {
        super.onPause();
        if(loadingid!=0){
            FileDownloader.getImpl().pause(loadingid);
        }
    }

    private int loadingid=0;

    public void gotGameInfo(GiftModel model){
        if(DeviceUtil.isInstallApp(this,model.getGame_package_name())){
            final Intent intent = this.getPackageManager().getLaunchIntentForPackage(model.getGame_package_name());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            startActivity(intent);
        }else{
            Intent intent= new Intent(this, GameDetailActivity.class);
            intent.putExtra("id",model.getGame_id());
            intent.putExtra("startdownload",true);
            startActivity(intent);
        }
    }

    private void startDownload(GiftModel model){
        StringBuilder builder = new StringBuilder(model.getGame_package_name().trim());
//        builder.append(gameid);
        builder.append(".apk");
        File file = new File(this.getExternalCacheDir(), builder.toString());
//        mSinglePath = FileDownloadUtils.getDefaultSaveRootPath()+
////                File.separator+"feifei_save"+
//                File.separator+model.getGame_package_name().trim()+".apk";;
        String mSinglePath = file.getAbsolutePath();
        BaseDownloadTask singleTask = FileDownloader.getImpl().create(model.getGame_urlfile())
//                .setPath(mSinglePath,false)
                .setPath(mSinglePath,false)
                .setCallbackProgressTimes(1000)
                .setMinIntervalUpdateSpeed(1000);
        loadingid = singleTask.start();

    }







    private final List<Fragment> fragments = new ArrayList<>();
    private void initFragmentTab(){
        if (fragments.isEmpty()) {
            MoreGiftFragment moreGiftFragment = new MoreGiftFragment();
            Bundle bundle = new Bundle();
            bundle.putSerializable("modle",headModel.getPopular_giftpack());
            moreGiftFragment.setArguments(bundle);


            MoreGiftFragment myFragment = new MoreGiftFragment();
            Bundle bundlem = new Bundle();
            bundlem.putSerializable("modle",headModel.getMy_giftpack());
            bundlem.putBoolean("ismine",true);
            myFragment.setArguments(bundlem);

            fragments.add(moreGiftFragment);
            fragments.add(myFragment);
        }

        mMainViewPager.setOffscreenPageLimit(fragments.size());
        mMainViewPager.setAdapter(new CommonFragmentPagerAdapter(getSupportFragmentManager(), fragments));
        mMainTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mMainViewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                mMainViewPager.setCurrentItem(tab.getPosition());
            }
        });

        mMainViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mMainTabLayout.setScrollPosition(position, 0f, true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        final int tabCount = mMainTabText.length;
        for (int index = 0; index < tabCount; index++) {
            CustomFuliTabView tabView = new CustomFuliTabView(this);
            tabView.setIcon(mMainTabIconResourceId[index]);
            tabView.setText(mMainTabText[index]);
            TabLayout.Tab tab = mMainTabLayout.newTab();
            tab.setCustomView(tabView);
//            tab.setIcon(mMainTabIconResourceId[index]);
//            tab.setText(mMainTabText[index]);
            mMainTabLayout.addTab(tab.setTag(index));
        }
    }





    @OnClick(R.id.actvity_back)
    public void onBackClick(){
        finish();
    }
    @Override
    protected int getViewLayoutResourceId() {
        return R.layout.actviity_moregift;
    }




}
